package GameConfig

import (
	xml "misc/dom4g"
	log "misc/seelog"
	"os"
	cfg "utils/config"
)

const unitXmlPath = "GameCore/Units.xml"

type XmlUnit struct {
	Type      string
	Name      string
	HP        int
	MP        int
	MoveSpeed int
	Flags     map[string]bool
	Abilities []*xml.Element
	Weapons   []*xml.Element
}

var xmlUnitMap map[string]*XmlUnit

func loadXmlUnit() {
	path := cfg.Get()["GameConfigPath"] + unitXmlPath
	xmlUnitMap = make(map[string]*XmlUnit)
	f, err := os.Open(path)
	if err != nil {
		log.Info(err)
	}
	xmldoc, err2 := xml.LoadByStream(f)
	if err2 != nil {
		log.Info(err2)
	}
	for _, v := range xmldoc.Root().AllNodes() {
		unit := parseUnit(v)
		xmlUnitMap[unit.Name] = unit
	}
}

func GetXmlUnit(strName string) *XmlUnit {
	return xmlUnitMap[strName]
}

func parseUnit(node *xml.Element) *XmlUnit {
	unit := &XmlUnit{}
	strId, _ := node.AttrValue("Name")
	unit.Name = strId
	unit.HP, _ = node.IntAttr("HP")
	unit.MP, _ = node.IntAttr("MP")
	unit.Type = node.Name()
	unit.MoveSpeed, _ = node.IntAttr("MoveSpeed")
	//Flags
	flagNode := node.Node("Flags")
	if flagNode != nil {
		unit.Flags = make(map[string]bool)
		for _, flagNode := range flagNode.AllNodes() {
			if flagNode.Value == "true" {
				unit.Flags[flagNode.Name()] = true
			}
		}
	}
	//Abilities
	abiliNode := node.Node("Abilities")
	if abiliNode != nil {
		unit.Abilities = make([]*xml.Element, abiliNode.NodesLength())
		allNode := abiliNode.AllNodes()
		for i := 0; i < len(allNode); i++ {
			unit.Abilities[i] = allNode[i]
		}
	}
	//Weapons
	weaponNode := node.Node("Weapons")
	if weaponNode != nil {
		unit.Weapons = weaponNode.AllNodes()
	}
	return unit
}
